// Copyright (C) ZHENG Zhong <heavyzheng nospam-at gmail D0T com>
//
// $Id: sys_env_win32.hpp 229 2008-09-15 13:39:09Z heavyzheng $
//

#ifndef ZZHENG_UTILITY_SYS_ENV_WIN32_HPP_20080703__
#define ZZHENG_UTILITY_SYS_ENV_WIN32_HPP_20080703__

#include <zzheng/config.hpp>
#include <boost/scoped_array.hpp>
#include <windows.h>
#include <string>

#ifndef DOXYGEN_SHOULD_SKIP_THIS

namespace zzheng {
namespace sys {
namespace detail {

    //! Returns the win32 path separator character.
    //! \return the win32 path separator character.
    inline
    char path_sep_char() {
        return ';';
    }

    //! Returns the win32 file separator character.
    //! \return the win32 file separator character.
    inline
    char file_sep_char() {
        return '\\';
    }

    //! Returns the system variable value by name.
    //! \param name  the name of the system variable.
    //! \return the value of the system variable.
    inline
    std::string get_sys_var(const std::string& name) {
        // Try to retrieve the variable value and put it into the buffer.
        unsigned int buffer_size = 1024U;
        boost::scoped_array<char> buffer(new char[buffer_size]);
        buffer[0] = 0;
        DWORD count = GetEnvironmentVariable(name.c_str(), buffer.get(), buffer_size);
        // Check if the buffer is big enough to hold the variable value.
        if (count >= buffer_size) {
            buffer_size = count + 1; // buffer_size = count should be enough.
            buffer.reset(new char[buffer_size]);
            buffer[0] = 0;
            count = GetEnvironmentVariable(name.c_str(), buffer.get(), buffer_size);
        }
        // Check if the variable value is retrieved successfully.
        if (count > 0 && count < buffer_size) {
            return std::string(buffer.get());
        } else {
            return std::string();
        }
    }

    //! Sets (and overwrites if necessary) the system variable.
    //! \param name   the name of the system variable to set.
    //! \param value  the value of the system variable to set.
    //! \return true if the system variable is set successfully, false otherwise.
    inline
    bool set_sys_var(const std::string& name, const std::string& value) {
        BOOL success = SetEnvironmentVariable(name.c_str(), value.c_str());
        return (success != FALSE);
    }

} // namespace zzheng::sys::detail
} // namespace zzheng::sys
} // namespace zzheng

#endif // !DOXYGEN_SHOULD_SKIP_THIS

#endif // ZZHENG_UTILITY_SYS_ENV_WIN32_HPP_20080703__



